package com.zxy.study.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zxy.study.R;
import com.zxy.study.utils.LifeCycleLog;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.util.Locale;

/**
 * ToolBar的两种使用方式
 * 一：单独使用
 * 二：替代ActionBar使用
 * 1）需要继承AppCompatActivity（需要使用Theme.AppCompat类型的主体）,并且将主题设置成NoActiobBar,否则会报java.lang.IllegalStateException:
 * This Activity already has an action bar supplied by the window decor 的异常
 * 2）setSupportActionBar(ToolBar tooolbar) 方法，将ToolBar作为当前Activity的ActionBar使用
 */
public class ToolBarActivity extends AppCompatActivity {

    private Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toor_bar);

        mToolbar = findViewById(R.id.toolbar);

        //		initToolBar1();
        initToolBarInsteadActionBar();

        LifeCycleLog.logCreate(ToolBarActivity.class);
        LifeCycleLog.logCurTaskInfo(this);
        Log.d("lifecycle","toolbar height="+mToolbar.getHeight());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            test();
        }
    }

    TextToSpeech textToSpeech;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void test() {
        textToSpeech = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                int result = textToSpeech.setLanguage(Locale.US);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(ToolBarActivity.this, "不支持", Toast.LENGTH_SHORT).show();
                } else if (result == TextToSpeech.LANG_AVAILABLE) {
                    Toast.makeText(ToolBarActivity.this, "支持", Toast.LENGTH_SHORT).show();
                }

            }
        });


    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void speak() {
        textToSpeech.setPitch(0.5f);
        textToSpeech.setSpeechRate(0.5f);
        textToSpeech.speak("Hello World", TextToSpeech.QUEUE_ADD, null, null);
    }

    /**
     * ToolBar的单独使用
     */
    private void initToolBar1() {
        //设置左侧导航图标以及点击事件
        mToolbar.setNavigationIcon(R.mipmap.icon_base_back);
        mToolbar.setNavigationOnClickListener(v -> {
            showToast("点击返回");
            finish();
        });

        //设置标题以及子标题,这里指ToolBar自带的标题和子标题
        //        mToolbar.setTitle("我是标题");
        //        mToolbar.setSubtitle("我是子标题");

        //添加菜单按钮
        mToolbar.inflateMenu(R.menu.menu);
        //设置菜单按钮点击事件
        mToolbar.setOnMenuItemClickListener(item -> {
            showToast(item.getTitle().toString());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                speak();
            }
            return false;
        });

        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("我是自定义的标题");
    }

    /**
     * ToolBar替换ActionBar
     */
    private void initToolBarInsteadActionBar() {
        setSupportActionBar(mToolbar);

        ActionBar actionBar = getSupportActionBar();
        //给左上角图标的左边加上一个返回的图标,图标是系统默认的返回图标，可以不用再手动去设置图标
        actionBar.setDisplayHomeAsUpEnabled(true);
        //设置隐藏默认的标题
        actionBar.setDisplayShowTitleEnabled(false);

        //当然我么你也可以手动设置ToolBar左侧导航图标,必须在setSupportActionBar操作之后设置才有效
        // 也可以在属性中设置app:navigationIcon="@mipmap/icon_base_back"
        mToolbar.setNavigationIcon(R.mipmap.icon_base_back);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //在这里添加menu按键，默认会显示在右上角
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //左侧导航图标以及menu的点击事件在该方法中回调
        switch (item.getItemId()) {
            case android.R.id.home://ActionBar左侧导航图标的
                showToast("我是左上角的返回图标");
                break;
            case R.id.menu1://菜单按钮
                showToast("我是menu1");
                break;
            default:
                showToast(item.getTitle().toString());
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private boolean first = true;
    @Override
    protected void onStart() {
        super.onStart();
        LifeCycleLog.logStart(ToolBarActivity.class);
        Log.d("lifecycle","toolbar height="+mToolbar.getHeight());
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LifeCycleLog.logReStart(ToolBarActivity.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LifeCycleLog.logResume(ToolBarActivity.class);
        Log.d("lifecycle","toolbar height="+mToolbar.getHeight());
        mToolbar.post(()->{
            Log.d("lifecycle","View Post toolbar height="+mToolbar.getHeight());
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        LifeCycleLog.logPause(ToolBarActivity.class);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LifeCycleLog.logStop(ToolBarActivity.class);
    }
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		LifeCycleLog.logSaveInstanceState(ToolBarActivity.class);
		outState.putString("AAA","测试");
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		LifeCycleLog.logRestoreInstanceState(ToolBarActivity.class);
		if(savedInstanceState != null) {
			String test = savedInstanceState.getString("AAA");
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		Log.d("lifecycle", "ToolBarActivity onConfigurationChanged");
	}
    @Override
    protected void onDestroy() {
        LifeCycleLog.logDestroy(ToolBarActivity.class);

        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
            textToSpeech = null;
        }
        super.onDestroy();
    }
}
